package com.iman.sumer.web.space;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iman.common.Constants;
import com.iman.common.support.Page;
import com.iman.common.util.IdCreater;
import com.iman.sumer.service.space.ShareService;
import com.iman.sumer.util.LinkMessages;
import com.iman.sumer.vo.EditShareVo;
import com.iman.sumer.vo.sapce.SharePo;
import com.iman.sumer.vo.sapce.ShareVo;
import com.iman.sumer.vo.sapce.TagVo;
import com.iman.sumer.web.BaseController;

/**
 * 职业规划
 */
@Controller
@RequestMapping(value = "/sumer/share/*")
public class ShareController extends BaseController {
	 
	@Autowired
	private ShareService shareService;

	public static final Map<String, String> fileTypeMap = new HashMap<String, String>();
	static {
		fileTypeMap.put("doc", "WORD");
		fileTypeMap.put("docx", "WORD");
		fileTypeMap.put("xls", "EXCEL");
		fileTypeMap.put("xlsx", "EXCEL");
		fileTypeMap.put("ppt", "PPT");
		fileTypeMap.put("pptx", "PPT");
		fileTypeMap.put("pdf", "PDF");
		fileTypeMap.put("txt", "TEXT");
		fileTypeMap.put("jpg", "IMG");
		fileTypeMap.put("gif", "IMG");
		fileTypeMap.put("png", "IMG");
		fileTypeMap.put("bmp", "IMG");
		fileTypeMap.put("zip", "COMPRESS");
		fileTypeMap.put("rar", "COMPRESS");
	}

	/**
	 * 
	 * Function: 功能说明： 初始查询页面 使用说明：
	 * 
	 * @author wangxiaolei DateTime 2014年12月18日 上午12:01:51 返回类型: ModelAndView
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/init")
	public ModelAndView init(HttpServletRequest request,String showId) throws Exception {
	 
		return initShare(request, "0", "5", null,showId);
	}
	
	
	@RequestMapping(value = "/init/{showId}")
	public ModelAndView initShowId(HttpServletRequest request, @Valid @PathVariable String showId) throws Exception {
		return this.init( request,   showId);
	}

	
	@RequestMapping(value = "/initShare/{pageNo}/{pageSize}/{showId}")
	public ModelAndView initShare(HttpServletRequest request, @Valid @PathVariable String pageNo,
			@Valid @PathVariable String pageSize, @Valid @PathVariable String showId ) throws Exception {
		
	 
		return this.initShare(request, pageNo, pageSize, null, showId);
	}
	
	@RequestMapping(value = "/initShare/{pageNo}/{pageSize}")
	public ModelAndView initShare(HttpServletRequest request, @Valid @PathVariable String pageNo,
			@Valid @PathVariable String pageSize, String tagId, String showId) throws Exception {
		if (!StringUtils.isNumeric(pageNo)) {
			throw new IllegalArgumentException("无效分页参数");
		}
		if (!StringUtils.isNumeric(pageSize)) {
			throw new IllegalArgumentException("无效分页参数");
		}

		// 共享列表
		Map<String, Object> mapDmsg = new HashMap<String, Object>();
		mapDmsg.put(Constants.PAGE_INDEX_KEY, Integer.parseInt(pageNo));
		mapDmsg.put(Constants.PAGE_SIZE_KEY, Integer.parseInt(pageSize));
		if (StringUtils.isNotBlank(tagId)) {
			mapDmsg.put("tagId", Integer.parseInt(tagId));
		}
		Long userId = this.getUserIdInSession(request);
		mapDmsg.put( "userId", showId==null?userId.toString():showId);
		 
		if(showId == null){
			showId = userId.toString();
		}

		Page<ShareVo> pageShare = shareService.getSharePage(mapDmsg);
		List<TagVo> hostTag = shareService.getHostTag();

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("pageData", pageShare);
		model.put("hostTag", hostTag);
		model.put("tagList", shareService.getTagList());
		model.put("tagId", tagId);
		model.put("uploadURL", LinkMessages.getString("UPLOAD_URL"));
		model.put("downloadURL", LinkMessages.getString("DOWNLOAD_URL"));

		ModelAndView view = new ModelAndView("space/share", model);

		//  加入 给前台 是否是自己的数据 ，和  传递 showId   传递使用
		boolean isme = super.isMeData(request, showId);
		super.putShowId(view, showId, isme);
		
		
		// 每个做后都要加上这个
		putResourceSrc(view ,request );
		// 点击tab颜色
		view.addObject("tabstatus", "share");
		return view;
	}

	@RequestMapping(value = "/delSharedResource")
	@ResponseBody
	public Map<String, Integer> delSharedResource(HttpServletRequest request, Long id) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		Long userId = super.getUserIdInSession(request);
		try {
			shareService.delSharedResource(id,userId);
			map.put("state", 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	@RequestMapping(value = "/addShareResource")
	@ResponseBody
	public Map<String, Integer> addShareResource(HttpServletRequest request, SharePo sharePo) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		try {
			Long resourceId = IdCreater.getId();
			Map<String, Object> mapResource = new HashMap<String, Object>();
			mapResource.put("id", resourceId);
			mapResource.put("sharedResourceId", UUID.randomUUID().toString());
			mapResource.put("topic", sharePo.getTopic());
			mapResource.put("authorId", this.getUserIdInSession(request));
			mapResource.put("tagId", sharePo.getTagId());
			mapResource.put("needIntegral", sharePo.getNeedIntegral());

			Map<String, Object> mapFile = new HashMap<String, Object>();
			mapFile.put("fileName", sharePo.getFileName());
			mapFile.put("fileId", sharePo.getFileId());
			mapFile.put("fileType", tranferFileType(sharePo.getFileType()));
			mapFile.put("resourceId", resourceId);
			mapFile.put("fileSize", sharePo.getFileSize());

			shareService.insertShared(mapResource, mapFile);
			map.put("state", 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	@RequestMapping(value = "/addDownloadCnt")
	@ResponseBody
	public Map<String, Integer> addDownloadCnt(HttpServletRequest request, Long id) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		System.out.println("wanghongngnn"+id);
		try {
			
			System.out.println("hahahah"+id);
			shareService.addDownloadCnt(id);
			map.put("state", 1);
			System.out.println("jjjjjjj"+map.get("state"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/******************************************************************************************************************************/

	@RequestMapping(value = "/add")
	public ModelAndView add(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
	 
		ModelAndView view = new ModelAndView("space/share_add", model);

		// TODO 查询

		// 每个做后都要加上这个
		putResourceSrc(view ,request );
		// 点击tab颜色
		view.addObject("tabstatus", "share");
		return view;
	}

	/******************************************************************************************************************************/

	@RequestMapping(value = "/tag")
	public ModelAndView tag(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		 
		ModelAndView view = new ModelAndView("space/share_tag", model);
		Long userId = this.getUserIdInSession(request);
		super.putShowId(view, userId, false);

		// 每个做后都要加上这个
		putResourceSrc(view ,request );
		// 点击tab颜色
		view.addObject("tabstatus", "share");
		return view;
	}

	public String tranferFileType(String fileType) {
		if (fileType.indexOf("/") > -1) {
			fileType = fileType.substring(fileType.indexOf("/") + 1);
		}
		return fileTypeMap.get(fileType);
	}

	
	
	
	
	@RequestMapping(value = "/mainShare/{showId}")
	@ResponseBody
	public Map mainShare(HttpServletRequest request,    @Valid @PathVariable String showId) throws Exception {
		// 共享列表
		Map<String, Object> mapDmsg = new HashMap<String, Object>();
		mapDmsg.put(Constants.PAGE_INDEX_KEY,  (0));
		mapDmsg.put(Constants.PAGE_SIZE_KEY,   (5));
		mapDmsg.put( "userId",  showId);
		Page<ShareVo> pageShare = shareService.getSharePage(mapDmsg);
		 
		Map result = new HashMap ();
		List<Map> data = new ArrayList<Map>();
		
		for(ShareVo vo :pageShare.getData()){
			Map content = new HashMap();
			content.put("link", "http://www.zhuclass.com/resource/detail/"+vo.getId().toString() );
			content.put("title", vo.getTopic());
			content.put("fileType", vo.getFileType());
			content.put("fileSize", vo.getFileSize());
			data.add(content);
		}
		result.put("content", data);
		result.put("morelink", "http://space.zhuclass.com/sumer/share/init/");
		return result;
	}
	
	@RequestMapping(value = "/getSharedResourceById")
	@ResponseBody
	public Map<String,Object> getSharedResourceById(HttpServletRequest request,Long id){
		Map<String,Object> map=new HashMap<String,Object>();
		try{
		EditShareVo editShareVo=shareService.getSharedById(id.longValue());
		map.put("tagId",editShareVo.getTag_id());
		map.put("topic",editShareVo.getTopic());
		map.put("needIntegral",editShareVo.getNeed_integral());
		map.put("state",1);
		}catch(Exception e){
			e.printStackTrace();
		}
		return map;
	}
	
	
	@RequestMapping(value = "/UpdateSharedResourceById")
	@ResponseBody
	public Map<String,String> updateSharedResourceById(HttpServletRequest request,Long id,String topic,Long tag_id,int needIntegral){
		Map<String,String> result = new HashMap<String,String> ();
		try{
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("tagId",tag_id);
		map.put("topic",topic);
		map.put("needIntegral",needIntegral);
		map.put("id",id);
		shareService.updateShareResource(map);
		
		result.put("state", "1");
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
		
	}
}
